function getOffsiteSelectedResumes(type,property){
   var elements = $('.osearch_resumeswrap table td.resumetitle.'+type+' input:checkbox:checked').closest("tr.selectable");

   var resumes=[];
   elements.each(function(i,element){
      if (!property) {
         resumes.push($(element).attr('data-resumecode'));
      } else if (property == 'import') {
         if (!$('a.actions.import', element).hasClass('imported')) {
            resumes.push($(element).attr('data-resumecode'));
         }
      }
   });

   return resumes;
}

function procesOffsiteSelection(type){
   var selectedResumes = getOffsiteSelectedResumes(type);
   if(selectedResumes.length==0) {
      $('.headresumeName.'+type+'>span.name').html('简历名称');
      $('.headresumeName.'+type).nextAll('th').find("span").show();
      $('.osearch_resumeswrap table.'+type).removeClass('multiselect');
      $('.headresumeName.'+type+' .selectedAction').hide();
   }
   else {
      $('.osearch_resumeswrap table.'+type).addClass('multiselect');
      $('.headresumeName.'+type).nextAll('th').find("span").hide(); 
      var selection='已选择';
      if(selectedResumes.length>0){
         if(selectedResumes.length==1){
            selection+="1份简历";
         }else{
            selection+=selectedResumes.length+"份简历";
         }
      }
      $('.headresumeName.'+type+'>span.name').text(selection);
      $('.headresumeName.'+type+' .selectedAction').show();
   }
}

var wintop;
function setPosition_2(){
   wintop = $(window).scrollTop();
   var srheight = $(".offsite_highsearch_wrap").height();
   if(wintop>=(44+srheight-19)){
      $(".hr_navigate_static").addClass("hr_navigate_fixed");
      $(".offsitesearch_result").css('paddingTop','39px');
      $(".osearch_resumeswrap table").each(function(){
         if($(this).hasClass("multiselect")){
            $(this).find("thead").addClass("now_fixed");
         }
         else {
            $(this).find("thead").removeClass("now_fixed");
         }
      });
   }
   else{
      //清除第三搜搜索翻页时候设置的cookie
      $.cookie('scrolltotop',null, { path: '/'});
      $(".hr_navigate_static").removeClass("hr_navigate_fixed");
      $(".offsitesearch_result").css('paddingTop','0px');
      $(".osearch_resumeswrap table").each(function(){
         $(this).find("thead").removeClass("now_fixed");
      });
   }

}

jQuery(document).ready(function($) {
   procesOffsiteSelection('51job');
   procesOffsiteSelection('zhilian');
   procesOffsiteSelection('jiancai');

   if($.cookie('scrolltotop') != null) {
      var srheight = $(".offsite_highsearch_wrap").height();
      $(window).scrollTop(44+srheight-19);
      setPosition_2();
   };
   
   $(window).scroll(function(){
      setPosition_2();
   });
   
   $('.osearch_resumeswrap').on('click','.pagination ul li',function(){
      $.cookie('scrolltotop', "yes", { path: '/'});
   });

   // Sets the offsite_select_all checkbox behaviour :
   $('.offsite_select_all').click(function() {
      var type = $(this).data('type');
      if($('.offsite_select_all.'+type).prop('checked')){
         // Check all
         $('.osearch_resumeswrap tbody td.resumetitle.'+type+' input:checkbox').prop('checked', true);
         $('.osearch_resumeswrap tbody td.resumetitle.'+type+' input:checkbox').closest("tr").addClass('selected');
         $('.osearch_resumeswrap tbody td.resumetitle.'+type+' input:checkbox').closest("tr").next().addClass('selected');
      }else{
         // Uncheck all
         $('.osearch_resumeswrap tbody td.resumetitle.'+type+' input:checkbox').prop('checked', false);
         $('.osearch_resumeswrap tbody td.resumetitle.'+type+' input:checkbox').closest("tr").removeClass('selected');
         $('.osearch_resumeswrap tbody td.resumetitle.'+type+' input:checkbox').closest("tr").next().removeClass('selected');
      }
      procesOffsiteSelection(type);
      setPosition_2();
   });

   $('.osearch_resumeswrap').on('change', 'td.resumetitle input:checkbox',function(event) {
      var type = $(this).data('type');

      var selectedCount=$('.osearch_resumeswrap td.resumetitle.'+type+' input:checkbox:checked').length;
      $(this).closest("tr").toggleClass('selected');
      $(this).closest("tr").next().toggleClass('selected');
      if(!$(this).prop('checked')){
         $('.offsite_select_all.'+type).prop('checked',false);
      }else{
         if(selectedCount==$('td.resumetitle.'+type+' input:checkbox').length){
            $('.offsite_select_all.'+type).prop('checked',true);
         }
      }
      procesOffsiteSelection(type);
      setPosition_2();
   });

   // Set jobposition demands
   $('.selectsite_div').on('click', '#selectjobposition,#job_name', function() {
      var list_url = getUrlQuery(offsitesearch_joblist, "cview=1");
      var pjobid = $("#job_id").val();

      if(pjobid > 0) {
         var list_url = getUrlQuery(list_url, "jobid="+pjobid);
      }

      $(this).jobSelect({
         title: '选择职位',
         listurl: list_url,
         calendarview: function() {
            var target = $(this);
            var jobid = target.data('jobid');
            var jobtitle = target.data('jobtitle');
            var term_id = $('#syncinfo').data('termid');
            if(jobid){
               $("#job_name").val(jobtitle);
               $("#job_id").val(jobid);
               var sources = [];
               $("input[name='source[]']:checked").each(function(){
                  sources.push($(this).val());
               });

               var source = sources.join(','); 
               $.ajax({
                  type: "GET",
                  url: OC.filePath('resumes', 'ajax/search', 'fillsearchform.php'),
                  data: {jobid: jobid, source: source},
                  beforeSend: function(xhr, settings) {
                     showLoading(target, settings, null, {button:true});
                  },
                  success: function(result) {
                     $('#searchterms').html(result);
                     $("#id_state").jobLocation({
                        'getcityurl': getcityurl,
                        'getprovinceurl': getprovinceurl
                     });
                  }
               });
            }
            $('#floatcontainer').modal("hide");
            return false;
         }
      });
   });

   $("#id_state").jobLocation({
     'getcityurl': getcityurl,
     'getprovinceurl': getprovinceurl
   });

   // Set Search Terms
   var validator = {
      rules: {
         'source[]': { required:true},
         workexp: { digits:true},
         expect_salary: { digits:true},
         agefrom: { digits:true, min: 18, max: 65},
         ageto: { digits:true, min: 18, max: 65}
      },
      messages: {
         'source[]': {
            required: "该项必填",
         },
         workexp: {
            digits:  "请输入合法的数字",
         },
         expect_salary:{
            digits: "请输入合法的数字",
         },
         agefrom:{
            digits: "请输入数值为18至65的合法数字",
            min: "请输入数值为18至65的合法数字",
            max: "请输入数值为18至65的合法数字",
         },
         ageto:{
            digits: "请输入数值为18至65的合法数字",
            min: "请输入数值为18至65的合法数字",
            max: "请输入数值为18至65的合法数字",
         }
      },
      errorPlacement:function(error,element) {
         if ( element.attr("name") == "source[]" ) {
            error.insertAfter("#addinterviewer");
         } else {
            error.insertAfter(element);
         }
      },
      submitHandler: function(form) {
         var source = new Array(),jiancai_rule = true;
         $('input[name="source[]"]:checked').each(function(){
            if($(this).val() == 'jiancai'){
               if($('input[name="keyword"]').val() == ''){
                  jiancai_rule = false;
                  $("#keyworderr").jobUtil('showError', '选择建筑英才网进行人才搜索时，需输入关键字').fadeOut(3000);
               }
            }
         });

         if(jiancai_rule){
            $(form).ajaxSubmit({
               dataType: "json",
               beforeSubmit: function(data, form, options) {
                  $('.systeminfo', form).hide().html('');
                  if(!showLoading(form))
                     return false;
               },
               success: function(data) {
                  if ($.cookie('tab')) {
                     $.cookie('tab', null);
                  }
                  try {
                     if (data.error) {
                        $('.systeminfo', form).show().html(data.error);
                     } else if(data.success) {
                        var ntid = data.success.term_id;
                        var jobid = data.success.job_id;
                        var jobtitle = data.success.job_title;
                        $.cookie('offsetsearch_tid', ntid);
                        window.location.href = getUrlQuery(offsitesearch_url, "tid="+ntid+(jobid.length>0 ? "&jobid="+jobid:"")+(jobtitle.length>0 ? "&jobtitle="+jobtitle:""));
                     }
                  } catch(e) {
                     return false;
                  }
              }
            });
         }
      }
   };

   $("#offsite_search_form").validate(validator);

   $("#offsite_search_form #clear_form").click(function(){
      $(':input','#offsite_search_form').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
      $(':input','#offsite_search_form').not(':button, :submit, :reset, :hidden').removeAttr('checked').removeAttr('selected');
      $('#offsite_search_form input[name=state]').val('');
      $('#offsite_search_form input[name=city]').val('');
      $('#offsite_search_form input[name=job_id]').val('');
   });

   // maintain a history of previous status 
   var prevstatus = []; 
   var checkSearchResult = function() {
      // if(DEVELOPMENT_MODE) return;
      var term_id = $('#syncinfo').data('termid');
      var syncing = $('#syncinfo #syncing').data('syncing');

      if (!term_id || term_id.length <= 0 || !syncing || syncing <= 0) {
         return false;
      }

      var self = this; 

      $.ajax({
         type: 'GET',
         url: OC.filePath('resumes', 'ajax/search', 'checksearchresult.php'),
         data: { term_id: term_id },
         cache: false,
         success: function(result) {
            if(result.status === 'success') {
               var source = $('#search_tabs li.cur_li').data('source'); 
               var alldone = true; 

               $.each(result.data, function(t, p) {
                  if(t == source && !prevstatus[t]) {
                     prevstatus[t] = p;
                  }
 
                  $('#resumeList.'+t).find('span.status').text(p+'%'); 
                  if(p != 100) {
                     if(t == source) 
                        prevstatus[t] = p; 
                     alldone = false; 
                  }
                  else if(t == source) {
                     // check if we still in showSyncPopup
                     var syncto = $('#popup_syncto').data('syncto');
                     var inpopup = syncto && !$.isEmptyObject(syncto) ? true : false; 

                     if(!inpopup) {
                        // check if accountsetdialog is open (normally this could be last)
                        inpopup = $('div.accountsetdialog').filter(function(d) {
                           return $(this).css('display') != 'none'; 
                        }).length > 0; 
                     }

                     if(inpopup) {
                        alldone = false; 
                     }
                     else if(prevstatus[t] != p) {
                        //FIXME: when prevstatus[t] or p is 100, we should load it via ajax instead of reloading the page 
                        window.location.reload();
                     }
                     else {
                        // we need to check if content is ready. This might happen when p is 100 on first check 
                        if ($('#resumeList.'+t).children('tr').not('tr.checking').length <= 0) {
                           setTimeout(function() { window.location.reload();}, 5000)
                        }
                     }
                  }
                  else if ($('#search_tabs a.'+t).find('i').hasClass('loading')) {
                     $('#search_tabs a.'+t).attr('title','搜索完成').tooltip('destroy').data("needreload", true); 
                     $('#search_tabs a.'+t).find('i').removeClass('loading').addClass('downok');
                  }
               })

               // data not ready, continue to read 
               if(!alldone) {
                  setTimeout(function() { checkSearchResult(); }, 5000);
               }
            } else {
               setTimeout(function() { checkSearchResult(); }, 5000);
            }
         }
      });
   };

   setTimeout(function() { checkSearchResult(); }, 2000);

   var showSyncPopup = function() {
      // Check if needs to show popup
      if($('#popup_syncto').length > 0) {
         var syncto = $('#popup_syncto').data('syncto');

         if(!syncto || $.isEmptyObject(syncto)) 
            return; 

         var source = false, status = 1; 
         $.each(syncto, function(key, value) {
            if(key == 'pipapai') {
               delete syncto[key]; 
            }
            else if(!source) {
               source = key; 
               status = value; 
               delete syncto[key]; 
            }
         }); 

         if(!source) {
            return; 
         }

         if(!$.isEmptyObject(syncto)) {
            $('#popup_syncto').data('syncto', syncto); 
         } else {
            $('#popup_syncto').data('syncto', null);
         }

         if(source.length > 0) {
            var data = {
               type: source,
               syncaction: (status > 0 ? 'searchresumes' : 'login'), 
               term_id: $('#syncinfo').data('termid'),
               pageno: $('#syncinfo #'+source).data('nowpage')
            };
   
            // add dataction when status is 0 to track how to display the messages 
            if(status <= 0) {
               data.dataaction = 'searchresumes'; 
            }

            startSync(source, data, function() {
               setTimeout(function() { showSyncPopup(); }, 1);
            }, function() { 
               // nothing to track login 
            }, function() {
               // Do nothing here
            });
         }
      }
   };

   showSyncPopup();

   $('#search_tabs').on('click', 'li', function() {
      var target = $(this);
      var source = target.data('source');

      $.cookie('tab', source);
      $('#search_tabs li').attr('class','');
      target.addClass('cur_li');
      $('.resume_listtable').hide();
      $('.resume_listtable.'+source).show();

      // data is ready, we need to reload if it's not done 
      if($('a.'+source, target).data('needreload')) {
         window.location.reload();
      }

      setPosition_2();
   });

   function switchAdvancedSearch(key, val) {
      if(key == 'showsearch' || key == 'showmorejob' || 'showdetail' || 'showsearchresumedetails') {
         $.ajax({
            type: 'POST',
            url: OC.filePath('resumes', 'ajax', 'switchsearch.php'),
            data: {key: key, val: val},
            dataType: 'json',
            success: function(result){
               // do nothing
            }
         });
      }
   }
   // Show mode
   $('#offsitesearch_result').on('click', '.showways_close', function(){
      $(this).addClass('curselect');
      $('#offsitesearch_result .showways_open').removeClass('curselect');
      $('.control_tr .resumedetails').hide();
      $('.control_trselect').removeClass('tr_hovercolor').find('.clicktoggle').removeClass('clicktoggle_up');
      switchAdvancedSearch('showsearchresumedetails',0);
   });

   $('#offsitesearch_result').on('click', '.showways_open', function(){
      $(this).addClass('curselect');
      $('#offsitesearch_result .showways_close').removeClass('curselect');
      $('.control_tr .resumedetails').show();
      $('.control_trselect').addClass('tr_hovercolor').find('.clicktoggle').addClass('clicktoggle_up');
      switchAdvancedSearch('showsearchresumedetails',1);
   });

   $('#offsitesearch_result').on('click', '.resumetitle span.clicktoggle', function(){
      var target = $(this).closest('.resumetitle').parent().next().find('.resumedetails');
      if(target.is(':hidden')) {
         target.show();
         $(this).addClass('clicktoggle_up');
         var ppparent = $(this).parent().parent().parent(); 
         ppparent.addClass('tr_hovercolor');
         ppparent.next().removeClass('tdnoborder_bottom');
         ppparent.addClass('tdnoborder_bottom');
         ppparent.next().find(".resume_detailtd").css("borderBottom","1px solid #88a5b2");
      } else {
         target.hide();
         $(this).removeClass('clicktoggle_up');
         var ppparent = $(this).parent().parent().parent(); 
         ppparent.removeClass('tr_hovercolor');
         ppparent.next().addClass('tdnoborder_bottom');
         ppparent.removeClass('tdnoborder_bottom');
         ppparent.next().find(".resume_detailtd").css("borderBottom","0px");
      }
   });

   // Do import
   function importResumes(resumes, source){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }
      var nresumes = [];
      $.each(resumes,function(index,resume) {
         nresumes[nresumes.length++] = resume; 
      });

      if(nresumes.length >= 1) {
         var data = {
            type: source,
            syncaction: 'saveresumes',
            resumecode: JSON.stringify(nresumes)
         };

         startSync(source, data, function() {
            procesOffsiteSelection(source);
         });
      }
   }

   function do_hide(resumes, source){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }

      var nresumes = [];
      $.each(resumes,function(index,resume) {
         nresumes[nresumes.length++] = resume;
      })

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax/search', 'hide.php'),
         data: {resumecodes:JSON.stringify(nresumes), source: source},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            if(!showLoading($('.headresumeName span .'+source+' .sethide'), settings, null, {button:true})) return false;
         },
         success: function(result){
            if (result.status == 'success') {
               $.each(nresumes,function(index,resume){
                  var resume = $.trim(resume);
                  var tr = $('table.'+source+' tr.control_trselect').filterAttr('data-resumecode',resume);
                  var hideAction = tr.children("td.resumetitle").find('a.actions.sethide');
                  tr.addClass('hiddenresume');
                  hideAction.removeClass('dohide').addClass('sethided').attr('data-original-title','取消隐藏');
               });

               var hiddentr = $('table.'+source+' tr.hiddenresume');
               $('tr.yellowtrline.'+source+' b').html('本页已隐藏简历'+hiddentr.length+'份');
               $('tr.yellowtrline.'+source).show();
               procesOffsiteSelection(source);
            } else {
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   }

   function undo_hide(resumes, source){
      if(!$.isArray(resumes)){
         resumes=[resumes];
      }

      var nresumes = [];
      $.each(resumes,function(index,resume) {
         nresumes[nresumes.length++] = resume;
      })

      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax/search', 'show.php'),
         data: {resumecodes:JSON.stringify(nresumes), source: source},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            if(!showLoading($('.headresumeName span .'+source+' .sethided'), settings, null, {button:true})) return false;
         },
         success: function(result){
            if (result.status == 'success') {
               $.each(nresumes,function(index,resume){
                  var resume = $.trim(resume);
                  var tr = $('table.'+source+' tr').filterAttr('data-resumecode',resume);
                  var hideAction = tr.children("td.resumetitle").find('a.actions.sethide');
                  tr.removeClass('hiddenresume');
                  hideAction.removeClass('sethided').addClass('dohide').attr('data-original-title','隐藏');
               });
               var hiddentr = $('table.'+source+' tr.hiddenresume');
               if (hiddentr.length <= 0) {
                  $('tr.yellowtrline.'+source).hide();
               } else {
                  $('tr.yellowtrline.'+source+' b').html('本页已隐藏简历'+hiddentr.length+'份');
                  $('tr.yellowtrline.'+source).show();
               }
               procesOffsiteSelection(source);
            } else {
               OC.Notification.showHtml(result.error+'<span class="undo tclose">'+t('resumes', 'Close')+'</span>', 3000);
            }
         }
      })
   }

   // Do batch import
   $('#offsitesearch_result').on('click', '.headresumeName a.import', function(event) {
      var source = $(this).data('source');
      var resumes = getOffsiteSelectedResumes(source, 'import');

      if (resumes.length <= 0) {
         $('.import_confirm.'+source+' .confirmtext.import').hide();
         $('.import_confirm.'+source+' .confirmtext.imported').show();
      } else {
         $('.import_confirm.'+source+' .confirmtext.import b').text(resumes.length+"个下载数");
         $('.import_confirm.'+source+' .confirmtext.imported').hide();
         $('.import_confirm.'+source+' .confirmtext.import').show();
      }
      $('.import_confirm.'+source).modal();
   });

   // Do import
   $('#offsitesearch_result').on('click', 'table a.actions.import', function(event) {
      var tr = $(this).closest('tr');
      var source = tr.data('source');
      var resume = tr.data('resumecode');

      if ($(this).hasClass('imported')) {
         $('.import_confirm.'+source+' .confirmtext.import').hide();
         $('.import_confirm.'+source+' .confirmtext.imported').show();
      } else {
         $('.import_confirm.'+source+' .confirmtext.import b').text("1个下载数");
         $('.import_confirm.'+source+' .confirmtext.imported').hide();
         $('.import_confirm.'+source+' .confirmtext.import').show();
      }
      $('.import_confirm.'+source).data('resume', resume).modal();
   });

   // Import confirm
   $('#offsitesearch_result').on('click', '.import_confirm .ppp_bluebtn', function(event) {
      var source = $(this).closest(".import_confirm").data('source');
      $('.import_confirm.'+source).modal("hide");
      var resumes;
      var resume = $('.import_confirm.'+source).data('resume');

      if (resume) {
         resumes = $.trim(resume);
         $('.import_confirm.'+source).data('resume', '');
      } else {
         resumes = getOffsiteSelectedResumes(source);
      }

      importResumes(resumes,source);
      return false;
   });

   // Do batch hide
   $('#offsitesearch_result').on('click', '.headresumeName a.sethide', function(event) {
      var source = $(this).data('source');
      var resumes = getOffsiteSelectedResumes(source);
      do_hide(resumes, source);
   });

   // Do batch unhide
   $('#offsitesearch_result').on('click',  '.headresumeName a.sethided', function(event) {
      var source = $(this).data('source');
      var resumes = getOffsiteSelectedResumes(source);
      undo_hide(resumes, source);
   });

   // Do hide
   $('#offsitesearch_result').on('click',  'table a.actions.dohide', function(event) {
      var tr = $(this).closest('tr');
      var source = tr.data('source');
      var resume = tr.data('resumecode');
      do_hide(resume, source);
   });

   // Do unhide
   $('#offsitesearch_result').on('click', 'table a.actions.sethided', function(event) {
      var tr = $(this).closest('tr');
      var source = tr.data('source');
      var resume = tr.data('resumecode');
      undo_hide(resume, source);
   });

   // Pagination control
    $('#offsitesearch_result').on('click', '.offsitepagination ul li', function() {
      var elem = $(this).parent('ul');
      var target = $(this);
      var source = elem.data('type');
      var termid = $('#syncinfo').data('termid');
      var pageno = target.data('page');

      if (!pageno || source == 'pipapai') {
         return false;
      }

      var delaytaskid = $('.resume_listtable.'+source).data('delaytaskid');
      var data = {
         source: source,
         term_id: termid,
         page_num: pageno,
         delaytask_id: delaytaskid
      };

      $.ajax({
         async: false,
         type: 'POST',
         url: OC.filePath('resumes', 'ajax/search', 'pageturn.php'),
         data: data,
         cache: false,
         success: function(result) {
            if (result.status == 'success') {
               window.location.reload();
            } else {
               // alert(result.error);
            }
         }
      });

   });

   // Show hidden resumes
    $('#offsitesearch_result').on('click', '.expand_hidden', function(event) {
      var target = $(this);
      var source = target.data('source');
      var stats = target.data('stats');

      if (!source)
         return false;

      if (stats == 'hidden') {
         $('table.'+source+' tr.hiddenresume').addClass('selectable').show();
         $('table.'+source+' tr.hiddenresume').next('tr').show();
         target.data('stats', 'shown').html('收起');
      } else if (stats == 'shown') {
         $('table.'+source+' tr.hiddenresume').removeClass('selectable').hide();
         $('table.'+source+' tr.hiddenresume').next('tr').hide();
         target.data('stats', 'hidden').html('展开');
      } else {
         $('table.'+source+' tr.hiddenresume').addClass('selectable').show();
         $('table.'+source+' tr.hiddenresume').next('tr').show();
         target.data('stats', 'shown').html('收起');
      }

      procesOffsiteSelection(source);
      return false;
   });

   // enable the button after js loads 
   $('.ppp_bluebtn.srh_subbtn').attr('disabled', false);

   $('.selectsite_ul').on('click', 'li input', function(event) {
      var cs_cookie = [];
      $(".selectsite_ul input[name='source[]']:checked").each(function(){
         cs_cookie.push($(this).val());
      });
      // Save chosen site into cookie
      $.cookie('chosen_site', cs_cookie);
   });

   $("td.resumetitle a.name").click(function(){
      $(this).closest(".control_trselect").removeClass("bold");
   });

})
